using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using WxMpApiDemo.Models;
using WxMpApiDemo.Services;

namespace WxMpApiDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly IJiuChunTangService _jiuChunTangService1;
        private string _currentEventId;

        public MainWindow()
        {
            InitializeComponent();
            ReportUrlTextBox.Text = "https://file.tcmhyg.com/report638929453122220542.pdf?Expires=1757924514&OSSAccessKeyId=LTAI5tJuVnVfFyd6n1NQX64W&Signature=aoPI5feO8QzF0OvDExvd8dS2lW8%3D";
        }

        public MainWindow(IJiuChunTangService jiuChunTangService)
        {
            InitializeComponent();
            _jiuChunTangService1 = jiuChunTangService;
            ReportUrlTextBox.Text = "https://file.tcmhyg.com/report638929453122220542.pdf?Expires=1757924514&OSSAccessKeyId=LTAI5tJuVnVfFyd6n1NQX64W&Signature=aoPI5feO8QzF0OvDExvd8dS2lW8%3D";
        }

        /// <summary>
        /// 获取Token按钮点击事件
        /// </summary>
        private async void GetTokenButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TokenResultTextBox.Text = "正在获取Token...";
                bool forceRefresh = ForceRefreshCheckBox.IsChecked ?? false;
                
                var token = await _jiuChunTangService1.GetAccessTokenAsync(forceRefresh);
                TokenResultTextBox.Text = $"Token获取成功：{token}";
            }
            catch (Exception ex)
            {
                TokenResultTextBox.Text = $"获取Token失败：{ex.Message}";
                MessageBox.Show($"错误：{ex.Message}", "获取Token失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取二维码按钮点击事件
        /// </summary>
        private async void GetQrCodeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                QrCodeResultTextBox.Text = "正在获取二维码...";
                QrCodeImage.Source = null;

                SceneStrTextBox.Text = SceneStrTextBox.Text + DateTime.Now.ToString("HHmmssfff");
                string sceneStr = SceneStrTextBox.Text;
                if (string.IsNullOrWhiteSpace(sceneStr))
                {
                    MessageBox.Show("请输入场景值", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                if (!int.TryParse(ExpireSecondsTextBox.Text, out int expireSeconds) || expireSeconds <= 0)
                {
                    MessageBox.Show("请输入有效的过期时间", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                var qrCodeResponse = await _jiuChunTangService1.CreateQrCodeAsync(sceneStr, expireSeconds);
                _currentEventId = sceneStr;
                EventIdTextBox.Text = _currentEventId;
                ReportEventIdTextBox.Text = _currentEventId;
                
                QrCodeResultTextBox.Text = $"二维码获取成功：\n" +
                                          $"expire_seconds: {qrCodeResponse.expire_seconds}\n" +
                                          $"image_url: {qrCodeResponse.image_url}\n" +
                                          $"errmsg: {qrCodeResponse.errmsg}\n" +
                                          $"errcode: {qrCodeResponse.errcode}";
                
                // 加载二维码图片
                if (!string.IsNullOrEmpty(qrCodeResponse.image_url))
                {
                    try
                    {
                        var bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.UriSource = new Uri(qrCodeResponse.image_url);
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        QrCodeImage.Source = bitmap;
                    }
                    catch (Exception imgEx)
                    {
                        QrCodeResultTextBox.Text += $"\n\n加载二维码图片失败：{imgEx.Message}";
                    }
                }
            }
            catch (Exception ex)
            {
                QrCodeResultTextBox.Text = $"获取二维码失败：{ex.Message}";
                MessageBox.Show($"错误：{ex.Message}", "获取二维码失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 查询扫码状态按钮点击事件
        /// </summary>
        private async void CheckScanStatusButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ScanStatusResultTextBox.Text = "正在查询扫码状态...";
                
                string eventId = EventIdTextBox.Text;
                if (string.IsNullOrWhiteSpace(eventId))
                {
                    MessageBox.Show("请输入事件ID", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                var statusResponse = await _jiuChunTangService1.GetScanStatusAsync(eventId);
                
                ScanStatusResultTextBox.Text = $"扫码状态查询成功：\n" +
                                              $"是否已扫码: {(statusResponse.scanned ? "是" : "否")}\n" +
                                              $"OpenID: {statusResponse.openId}\n" +
                                              $"扫码时间: {statusResponse.scannedTime}\n" +
                                              $"eventId: {statusResponse.eventId}";
                                            
                
                if (statusResponse.scanned && !string.IsNullOrEmpty(statusResponse.openId))
                {
                    OpenIdTextBox.Text = statusResponse.openId;
                }
            }
            catch (Exception ex)
            {
                ScanStatusResultTextBox.Text = $"查询扫码状态失败：{ex.Message}";
                MessageBox.Show($"错误：{ex.Message}", "查询扫码状态失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 回传报告按钮点击事件
        /// </summary>
        private async void SendReportButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ReportResultTextBox.Text = "正在回传报告...";
                
                string eventId = ReportEventIdTextBox.Text;
                string openId = OpenIdTextBox.Text;
                string reportId = ReportIdTextBox.Text;
                string reportUrl = ReportUrlTextBox.Text;
                string payload = PayloadTextBox.Text;
                
                if (string.IsNullOrWhiteSpace(eventId) || string.IsNullOrWhiteSpace(openId) ||
                    string.IsNullOrWhiteSpace(reportId) || string.IsNullOrWhiteSpace(reportUrl))
                {
                    MessageBox.Show("请填写所有必填字段", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                var reportData = new ReportCallbackRequest
                {
                    eventId = eventId,
                    openId = openId,
                    reportType = "jingluo",
                    reportId = reportId,
                    reportUrl = reportUrl,
                    payload = payload
                };
                
                var response = await _jiuChunTangService1.SendReportCallbackAsync(reportData);
                
                ReportResultTextBox.Text = $"errcode {response.errcode}：\n" +
                                          $"errmsg: {response.errmsg}";
            }
            catch (Exception ex)
            {
                ReportResultTextBox.Text = $"回传报告失败：{ex.Message}";
                MessageBox.Show($"错误：{ex.Message}", "回传报告失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}